"use client"
import { useState, useEffect } from "react"
import { useRouter } from 'next/navigation';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import axios from "axios"
import Web3 from 'web3';

let web3;
let provide;
let userAccount;
let signedMessage;

// const verifyMessage = async () => {
//   const recoveredAddress = web3.eth.accounts.recover('Hello,sign this message!', "0xa201a04439139169742a5d9de3700f91e8623ef18a850853738dc76c65f15506436162f49a1d9375d95bafe3ea6bebc070dd997d1a8105856a3f84518010476d1b");
//   console.log(recoveredAddress);
// };

export function Login() {
  const router = useRouter();
  const [isLoginWithEmail, setIsLoginWithEmail] = useState(true)
  const [email, setEmail] = useState()
  const [code, setCode] = useState()
  const [isSending, setIsSending] = useState(false);
  const [timer, setTimer] = useState(0);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      console.log('Router is ready:', router.isReady);
    }
    let interval;
    if (timer > 0) {
      interval = setInterval(() => {
        setTimer(prevTimer => prevTimer - 1);
      }, 1000);
    } else if (timer === 0) {
      clearInterval(interval);
      setIsSending(false)
    }
    return () => clearInterval(interval);
  }, [timer, router]);

  const emailChange = (event) => {
    setEmail(event.target.value)
  }

  const codeChange = (event) => {
    setCode(event.target.value)
  }

  const signIn = () => {
    let data = JSON.stringify({
      "email": email,
      "code": code
    });

    let config = {
      method: 'post',
      withCredentials: true,
      maxBodyLength: Infinity,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/authenticate/email`,
      headers: {
        'Content-Type': 'application/json'
      },
      data: data
    };

    axios.request(config)
      .then((response) => {
        console.log(response.status);
        if (response.status == 200) {
          router.push("/chatgpt-4o")
        }

      })
      .catch((error) => {

      });
  }

  const sendEmail = () => {
    setIsSending(true);
    setTimer(60);
    let data = JSON.stringify({
      "email": email
    });

    let config = {
      method: 'post',
      maxBodyLength: Infinity,
      withCredentials: true,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/send-code`,
      headers: {
        'Content-Type': 'application/json',
      },
      data: data
    };

    axios.request(config)
      .then((response) => {
        console.log(JSON.stringify(response.data));
      })
      .catch((error) => {
        console.log(error);
      });
  }

  async function connectWallet(walletType) {

    if (walletType == "okxwallet") {
      if (typeof window.okxwallet !== 'undefined') {
        web3 = new Web3(window.okxwallet);
        provide = window.okxwallet;
      } else {
        alert('okxwallet not installed!');
        return
      }

    } else if (walletType == "metamask") {
      console.log(123);

      if (typeof window.ethereum !== 'undefined') {
        web3 = new Web3(window.ethereum);
        provide = window.ethereum
      } else {
        alert('metamask not installed!');
        return;
      }
    }

    try {
      // 请求账户访问
      await provide.request({ method: 'eth_requestAccounts' });

      // 尝试切换到Sepolia测试网
      try {
        await provide.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: '0xaa36a7' }] // Sepolia的Chain ID是11155111，十六进制为0xaa36a7
        });
        console.log('Successfully switched to Sepolia network');

      } catch (switchError) {
        // 这个错误代码表明该网络还没有被添加到MetaMask
        if (switchError.code === 4902) {
          try {
            await provide.request({
              method: 'wallet_addEthereumChain',
              params: [{
                chainId: '0xaa36a7',
                chainName: 'Sepolia Test Network',
                rpcUrls: ['https://rpc.sepolia.org'], // 替换为有效的Sepolia RPC URL
                nativeCurrency: {
                  name: 'Sepolia ETH',
                  symbol: 'ETH',
                  decimals: 18
                },
                blockExplorerUrls: ['https://sepolia.etherscan.io'] // 替换为有效的区块浏览器URL
              }]
            });
            console.log('Successfully added and switched to Sepolia network');
          } catch (addError) {
            console.error('Failed to add Sepolia network', addError);
          }
        } else {
          console.error('Failed to switch to Sepolia network', switchError);
        }
      }
    } catch (error) {
      console.error('User rejected the request', error);
    }
    try {
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      userAccount = (await web3.eth.getAccounts())[0];
      signMessage()

    } catch (error) {
      console.error('connect MetaMask error:', error);
    }
    //signMessage()
  }

  async function signMessage() {
    //const provider = new ethers.providers.Web3Provider(window.ethereum);
    const accounts = await web3.eth.getAccounts();
    //setAccount(accounts[0]);
    const message = 'Hello,sign this message!';
    const signedMessage = await web3.eth.personal.sign(message, accounts[0], '');
    sendSignMessage(message, signedMessage, accounts[0])
  }

  async function sendSignMessage(message, signedMessage, address) {
    const axios = require('axios');
    let data = JSON.stringify({
      "signMessage": signedMessage,
      "message": message,
      "walletAddress": address
    });

    let config = {
      method: 'post',
      maxBodyLength: Infinity,
      withCredentials: true,
      url: `${process.env.NEXT_PUBLIC_API_URL}/api/authenticate/wallet`,
      headers: {
        'Content-Type': 'application/json'
      },
      data: data
    };

    axios.request(config)
      .then((response) => {
        if (response.status == 200) {
          router.push("/chatgpt-4o")
        }
      })
      .catch((error) => {
        console.log(error);
      });

  }

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-[#e4e5f8] bg-opacity-70">
      <div>
        {isLoginWithEmail ? (
          <Card>
            <CardHeader className="grid">
              <div className="flex">
                <CardTitle className="text-2xl">Login with Email</CardTitle>
                <Link href="/" className="ml-auto"><button>✕</button></Link>
              </div>
              <CardDescription>Enter your email and the verification code we sent you to sign in.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-2">
                <Label htmlFor="email">Email</Label>
                <Input id="email" onChange={emailChange} value={email} />
              </div>
              <div className="grid grid-cols-[1fr_auto] gap-2 items-end">
                <div className="grid gap-2">
                  <Label htmlFor="code">Verification Code</Label>
                  <Input onChange={codeChange} value={code} />
                </div>
                <Button disabled={isSending || timer > 0} onClick={sendEmail} variant="outline">{isSending ? timer : 'get code'}</Button>
              </div>
            </CardContent>
            <CardFooter>
              <Button onClick={signIn} className="w-full">Sign In</Button>
            </CardFooter>
            <div className="flex justify-center mt-4 mb-4">
              <Button
                variant={isLoginWithEmail ? "outline" : "default"}
                onClick={() => setIsLoginWithEmail(true)}
                className="mr-2"
              >
                Login with Email
              </Button>
              <Button variant={!isLoginWithEmail ? "outline" : "default"} onClick={() => setIsLoginWithEmail(false)}>
                Login with Web3 Wallet
              </Button>
            </div>
          </Card>
        ) : (
          <Card>
            <CardHeader>
              <CardTitle className="text-2xl">Login with Web3 Wallet</CardTitle>
              <CardDescription>Connect your Web3 wallet to sign in to your account.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-2">
                <Label htmlFor="wallet">Web3 Wallet</Label>
                <Button onClick={() => connectWallet("metamask")} variant="outline" className="w-full">
                  Connect MetaMak
                </Button>
              </div>
              <div className="grid gap-2">
                <Button onClick={() => connectWallet("okxwallet")} variant="outline" className="w-full">
                  Connect OKX Wallet
                </Button>
              </div>
            </CardContent>

            <div className="flex justify-center mt-4 mb-4">
              <Button
                variant={isLoginWithEmail ? "outline" : "default"}
                onClick={() => setIsLoginWithEmail(true)}
                className="mr-2"
              >
                Login with Email
              </Button>
              <Button variant={!isLoginWithEmail ? "outline" : "default"} onClick={() => setIsLoginWithEmail(false)}>
                Login with Web3 Wallet
              </Button>
            </div>
          </Card>
        )}
      </div>
    </div>
  )
}
